<template>
  <view class="points-history-page">
    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view v-for="(tab, index) in filterTabs" :key="index" :class="['tab-item', { active: currentTab === tab.value }]"
        @click="switchTab(tab.value)">
        {{ tab.label }}
      </view>
    </view>

    <!-- 积分记录列表 -->
    <view class="records-list">
      <view v-for="(record, index) in recordsList" :key="index" class="record-item">
        <view class="record-icon">
          <text>{{ getRecordIcon(record.type, record.source) }}</text>
        </view>

        <view class="record-info">
          <view class="record-title">{{ getRecordTitle(record.source) }}</view>
          <view class="record-time">{{ formatTime(record.created_at || record.createdAt) }}</view>
          <view class="record-desc" v-if="record.description">{{ record.description }}</view>
        </view>

        <view class="record-amount" :class="[getRecordTypeForClass(record)]">
          <text>{{ getAmountDisplay(record) }}</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="recordsList.length === 0 && !isLoading">
        <image src="/static/icons/empty.png" class="empty-icon" />
        <view class="empty-text">暂无积分记录</view>
        <view class="empty-tip">快去赚取积分吧！</view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <view v-if="isLoadingMore" class="loading-text">加载中...</view>
        <view v-else class="load-more-btn" @click="loadMore">加载更多</view>
      </view>
    </view>
  </view>
</template>

<script>
import { getPointsHistory } from '@/api/points.js'

export default {
  name: 'PointsHistoryPage',

  data() {
    return {
      currentTab: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '获得', value: 'earn' },
        { label: '消费', value: 'consume' }
      ],
      recordsList: [],
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      isLoading: false,
      isLoadingMore: false
    }
  },

  onLoad(options) {
    this.initStatusBar()

    // 如果有传入类型参数，设置默认筛选
    if (options.type) {
      this.currentTab = options.type
    }



    this.loadPointsHistory()
  },

  onReachBottom() {
    if (this.hasMore && !this.isLoadingMore) {
      this.loadMore()
    }
  },

  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    /**
     * 初始化状态栏高度
     */
    initStatusBar() {
      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0

      if (typeof document !== 'undefined' && document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', statusBarHeight * 2 + 'rpx')
      }
    },

    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },

    /**
     * 切换标签
     */
    switchTab(tab) {
      if (this.currentTab === tab) return

      this.currentTab = tab
      this.refreshData()
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      this.currentPage = 1
      this.recordsList = []
      this.hasMore = true
      await this.loadPointsHistory()
    },

    /**
     * 加载积分记录
     */
    async loadPointsHistory() {
      if (this.isLoading) return

      this.isLoading = true

      try {
        const params = {
          page: this.currentPage,
          limit: this.pageSize
        }

        // 只有在不是'all'时才添加type参数
        if (this.currentTab !== 'all') {
          params.type = this.currentTab
        }

        const result = await getPointsHistory(params)

        if (result.success) {
          const data = result.data
          const records = data.records || data.transactions || []

          if (this.currentPage === 1) {
            this.recordsList = records
          } else {
            this.recordsList.push(...records)
          }

          this.hasMore = this.currentPage < (data.totalPages || data.pagination?.total || 1)
        } else {
          this.showError(result.message || '加载积分记录失败')
        }
      } catch (error) {
        console.error('加载积分记录失败:', error)
        this.showError('加载积分记录失败')
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 加载更多
     */
    async loadMore() {
      if (!this.hasMore || this.isLoadingMore) return

      this.isLoadingMore = true
      this.currentPage++

      try {
        await this.loadPointsHistory()
      } finally {
        this.isLoadingMore = false
      }
    },

    /**
     * 获取记录图标
     */
    getRecordIcon(type, source) {
      // 兼容不同的type字段值
      const recordType = type === 'earn' || type === 'add' || (typeof type === 'undefined' && source === 'ad_watch') ? 'earn' : 'consume'

      if (recordType === 'earn') {
        const earnIcons = {
          'ad_watch': '�',
          'invite_register': '👥',
          'invite_consume': '🎁',
          'recharge_bonus': '💰',
          'activity': '🎉',
          'admin_adjust': '⚙️'
        }
        return earnIcons[source] || '💰'
      } else {
        const consumeIcons = {
          'product_exchange': '🛍️',
          'print_service': '🖨️',
          'consume': '💸',
          'admin_adjust': '⚙️'
        }
        return consumeIcons[source] || '💸'
      }
    },

    /**
     * 获取记录标题
     */
    getRecordTitle(source) {
      const titleMap = {
        'ad_watch': '观看广告',
        'invite_register': '邀请注册',
        'invite_consume': '邀请消费',
        'recharge_bonus': '充值奖励',
        'activity': '活动奖励',
        'product_exchange': '商品兑换',
        'print_service': '打印服务',
        'admin_adjust': '系统调整'
      }
      return titleMap[source] || '其他'
    },

    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      if (!timestamp) return '未知时间'

      try {
        const date = new Date(timestamp)
        if (isNaN(date.getTime())) {
          return '时间格式错误'
        }

        const now = new Date()
        const diff = now - date

        if (diff < 60000) { // 1分钟内
          return '刚刚'
        } else if (diff < 3600000) { // 1小时内
          return Math.floor(diff / 60000) + '分钟前'
        } else if (diff < 86400000) { // 1天内
          return Math.floor(diff / 3600000) + '小时前'
        } else if (diff < 86400000 * 7) { // 1周内
          return Math.floor(diff / 86400000) + '天前'
        } else {
          return date.toLocaleDateString()
        }
      } catch (error) {
        console.error('时间格式化错误:', error)
        return '时间格式错误'
      }
    },

    /**
     * 获取记录类型
     */
    getRecordType(record) {
      // 基于type字段判断，如果type不存在则基于amount判断
      if (record.type === 'earn' || record.type === 'add' || record.type === 'activity') {
        return 'earn'
      } else if (record.type === 'consume' || record.type === 'spend') {
        return 'consume'
      } else {
        // 如果type字段不明确，基于amount判断
        return parseFloat(record.amount) >= 0 ? 'earn' : 'consume'
      }
    },

    /**
     * 获取记录类型的CSS类名
     */
    getRecordTypeForClass(record) {
      return this.getRecordType(record)
    },



    /**
     * 获取金额显示
     */
    getAmountDisplay(record) {
      const amount = parseFloat(record.amount || 0)

      // 如果amount本身就是负数，直接显示
      if (amount < 0) {
        return amount.toString()
      }

      // 如果amount是正数，根据type决定显示方式
      const type = this.getRecordType(record)
      if (type === 'consume') {
        return `-${amount}`
      } else {
        return `+${amount}`
      }
    },

    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.points-history-page {
  min-height: 100vh;
  background: #f5f5f5;
}

// 导航栏样式
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: #667eea;
  position: relative;
  z-index: 100;
  box-sizing: border-box;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.7;
    transform: scale(0.95);
  }
}

.back-icon {
  font-size: 36rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.nav-right {
  width: 80rpx;
  height: 60rpx;
}

// 筛选标签
.filter-tabs {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16rpx;
  font-size: 26rpx;
  color: #666;
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &.active {
    background: #667eea;
    color: white;
  }

  &:active {
    transform: scale(0.95);
  }
}

// 记录列表
.records-list {
  padding: 0 20rpx 20rpx;
}

.record-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.record-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.record-info {
  flex: 1;
}

.record-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.record-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.record-desc {
  font-size: 22rpx;
  color: #666;
}

.record-amount {
  font-size: 28rpx;
  font-weight: bold;

  &.earn {
    color: #52c41a;
  }

  &.consume {
    color: #ff4d4f;
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
  color: #999;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 32rpx;
  margin-bottom: 16rpx;
}

.empty-tip {
  font-size: 26rpx;
  color: #ccc;
}

// 加载更多
.load-more {
  text-align: center;
  padding: 40rpx;
}

.loading-text,
.load-more-btn {
  font-size: 26rpx;
  color: #666;
  padding: 16rpx 32rpx;
  border-radius: 20rpx;
  background: #f8f9fa;
  display: inline-block;
}

.load-more-btn {
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    background: #e9ecef;
    transform: scale(0.95);
  }
}
</style>